import React from 'react';
import $ from "jquery";
import { notification } from 'antd';
import { pathPrefix } from '../util/fetchTool';

export const login = (data = {}) => () => {
    return $.ajax(`${pathPrefix}/login`, {
        processData: false,
        contentType: 'application/json',
        method: 'POST',
        data: JSON.stringify(data),
    }).done(response => {
        if (response && response.success) {
            return response.data;
        }
        return null;
    }).fail((XHR, textStatus, errorThrown) => {
        notification.error({
            message: `登录：${textStatus}`,
            description: <pre>{errorThrown}</pre>,
            duration: 0,
        });
    });
};

export const getCaptcha = (rand = Date.now()) => () => {
    return $.ajax(`${pathPrefix}/getCaptcha?date=${rand}`, {
        headers: {
            Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            // 'X-Requested-With': 'XMLHttpRequest'
        },
        dataType: 'text',
        // dataType: 'blob',
        // dataType: 'binary',
        // processData: false,
    }).done(response => {
        /* window.URL = window.URL || window.webkitURL || window.mozURL;
        const blob = response,
            img = document.createElement('img');
        img.onload = function () {
            window.URL.revokeObjectURL(img.src);
            console.log(222, img.src);
        };
        img.src = window.URL.createObjectURL(blob); */
        return `${response}`;
    }).fail((XHR, textStatus, errorThrown) => {
        notification.error({
            message: `图片验证码：${textStatus}`,
            description: <pre>{errorThrown}</pre>,
            duration: 0,
        });
    });
}

export const register = (key = '', data = {}) => () => {
    const url = {
        "1": `${pathPrefix}/front/register`,
        "2": `${pathPrefix}/front/companyRegister`,
    };
    return $.ajax(url[key], {
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
    }).done(response => {
        if (response && response.success) {
            return response;
        }
        return null;
    }).fail((XHR, textStatus, errorThrown) => {
        notification.error({
            message: `注册：${textStatus}`,
            description: <pre>{errorThrown}</pre>,
            duration: 0,
        });
    });
}